package mdt.action;

import org.tigris.gef.base.Diagram;
import org.tigris.gef.base.Editor;
import org.tigris.gef.base.Globals;
import mdt.program.Displayer;
import mdt.program.GraphManager;
import mdt.program.GraphManager.GraphInfo;
import mdt.figure.FigTextEditorMDT;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;

/**
 * Created by lambert on 2016/6/20.
 */
public class SaveAction extends AbstractAction{
	public SaveAction() {
		super("Save");
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			Editor ce = Globals.curEditor();

			if (ce.getActiveTextEditor() != null) {
				((FigTextEditorMDT)ce.getActiveTextEditor()).endEditing();
			}

			GraphInfo infoSet = null;
			if (e.getSource() instanceof GraphInfo) {
				infoSet = (GraphInfo)e.getSource();
			} else {
				infoSet = GraphManager.getActiveGraphInfo();
			}

			Diagram diagram = infoSet.diagram;
			File file;
			if (infoSet.file == null) {
				do {
					JFileChooser chooser = new JFileChooser(GraphManager.getLastVisitedDir());
					chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
						@Override
						public boolean accept(File f) {
							if (f.isDirectory()) return true;
							if (f.getName().toLowerCase().endsWith(".mdt")) return true;
							return false;
						}

						@Override
						public String getDescription() {
							return "MDT files(*.mdt)";
						}
					});
					chooser.setDialogTitle("Saving " + infoSet.getTitle() + " ...");
					int result = chooser.showSaveDialog(Displayer.instance().getJFrame());
					if (result != JFileChooser.APPROVE_OPTION) {
						return;
					}

					file = chooser.getSelectedFile();
					GraphManager.setLastVisitedDir(file.getParentFile().getAbsolutePath());
					if (!file.getName().toLowerCase().endsWith(".mdt")) {
						file = new File(file.getParent() + File.separator + file.getName() + ".mdt");
					}
					if (file.exists()) {
						int res = JOptionPane.showConfirmDialog(Displayer.instance().getJFrame(),
								"File " + file.getName() + " already exists, overwrite?",
								"Overwrite?", JOptionPane.OK_CANCEL_OPTION);
						if (res == JOptionPane.CANCEL_OPTION) {
							continue;
						}
					}
					break;
				} while (true);
			} else {
				file = infoSet.file;
			}
			if (file != null) {
				Globals.showStatus("Writing " + file.getAbsolutePath() + "...");
				FileOutputStream f = new FileOutputStream(file);
				ObjectOutput s = new ObjectOutputStream(f);
				diagram.preSave();
				s.writeObject(diagram);
				diagram.postSave();
				Globals.showStatus("Wrote " + file.getAbsolutePath());
				f.close();

				infoSet.file = file;
				infoSet.setDirty(false);
				infoSet.setTitle(file.getName());
			}
		} catch (FileNotFoundException ignore) {
			System.out.println("got an FileNotFoundException");
		} catch (IOException ignore) {
			System.out.println("got an IOException");
			ignore.printStackTrace();
		}
	}

}
